package storage

import (
	"duoke/context"
	"duoke/utils/gfile"
	"github.com/gin-gonic/gin"
	"path/filepath"
)

var Local = new(localStorage)

type localStorage struct{}

// 本地保存
func (s *localStorage) Save(c *gin.Context, config *StructConfig) (*StructFile, error) {
	_, headers, err := c.Request.FormFile("file")
	if err != nil {
		return nil, err
	}
	// 文件后缀
	suffix := filepath.Ext(headers.Filename)
	// 默认保存路径
	storagePath := "./public/storage/"
	savePath := config.SavePath
	saveName := config.SaveName
	// 创建目录
	err = gfile.MakeDir(storagePath + savePath)
	if err != nil {
		return nil, err
	}
	// 保存文件到本地
	err = c.SaveUploadedFile(headers, storagePath+savePath+saveName)
	if err != nil {
		return nil, err
	}
	file := StructFile{
		Storage:      "local",
		OriginalName: headers.Filename,
		Name:         saveName,
		Size:         headers.Size,
		Suffix:       suffix,
		Type:         headers.Header.Get("Content-Type"),
		Path:         savePath + saveName,
		Url:          context.Global.StorageUrl + "/" + savePath + saveName,
	}
	return &file, nil
}

// 删除文件
func (s *localStorage) Del(path string) error {
	storagePath := "./public/storage/"
	return gfile.RemoveFile(storagePath + path)
}
